import { useState, useEffect } from 'react'

const useFullScreen = () => {
    const [isFullScreen, setIsFullScreen] = useState(document.fullscreenElement !== null)

    const toggleFullScreen = () => {
        if (!isFullScreen) {
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen()
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen()
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen()
            } else if (document.documentElement.msRequestFullscreen) {
                document.documentElement.msRequestFullscreen()
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen()
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen()
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen()
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen()
            }
        }
    }

    const handleKeyDown = (event: any) => {
        if (event.key === 'F11') {
            event.preventDefault()
            toggleFullScreen()
        }
    }

    useEffect(() => {
        const handleFullScreenChange = () => {
            setIsFullScreen(document.fullscreenElement !== null)
        }
        document.addEventListener('fullscreenchange', handleFullScreenChange)
        document.addEventListener('webkitfullscreenchange', handleFullScreenChange)
        document.addEventListener('mozfullscreenchange', handleFullScreenChange)
        document.addEventListener('MSFullscreenChange', handleFullScreenChange)
        document.addEventListener('keydown', handleKeyDown)
        return () => {
            document.removeEventListener('fullscreenchange', handleFullScreenChange)
            document.removeEventListener('webkitfullscreenchange', handleFullScreenChange)
            document.removeEventListener('mozfullscreenchange', handleFullScreenChange)
            document.removeEventListener('MSFullscreenChange', handleFullScreenChange)
            document.removeEventListener('keydown', handleKeyDown)
        }
    })

    return { isFullScreen, toggleFullScreen }
}

export default useFullScreen
